//
//  EditPanelNumberViewController.swift
//  ezyform
//
//  Created by MoennigQ on 15/8/19.
//  Copyright © 2019 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import MBProgressHUD
import RxCocoa
import RxSwift
//MARK: - 用于修改Panel和inverter的code
class EditBarcodeViewController: BaseViewController {
    let disposeBag = DisposeBag()
    var scanningType: ScanningType = .panel
    let customView = EditBarcodeViewView()
    var barcodeModel: PanelNumberImageDBModel!
    var index: Int = 0
    var serialsList: [PanelNumberImageDBModel]!
    override func viewDidLoad() {
        super.viewDidLoad()
        //
        switch self.scanningType {
        case .panel:
            self.serialsList = JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers
        case .inverter, .tank:
            self.serialsList = JobDetailModelHelper.shared.jobDetailModel.pvd_inverter_serial_numbers
        }
        self.barcodeModel = serialsList[self.index]
        self.initUI()
    }
    
    func initUI(){
        
        self.view = self.customView
        var naviTitle = ""
        switch self.scanningType {
        case .panel:
            naviTitle = R.string.localizable.editSerialsNumber("Panel")
        case .inverter:
            naviTitle = R.string.localizable.editSerialsNumber("Inverter")
        case .tank:
            naviTitle = R.string.localizable.editSerialsNumber("Tank")
        }
        self.customView.setTitleInfo(naviTitle)
        self.customView.setData(barcodeModel.image, code: barcodeModel.code )
        self.customView.saveBtn.rx.tap.subscribe { [weak self] _ in
            self?.saveBtnClick()
        }.disposed(by: self.disposeBag)
        self.customView.barcodeTextField.becomeFirstResponder()
    }
    @objc func saveBtnClick(){
        self.view.endEditing(true)//关闭键盘
        guard let data = self.customView.barcodeTextField.text else{
            return
        }
        let barcode = data.trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences(of: ",", with: "")
        if barcode == "" {
            Tool().showAlertViewWithOneBtn(message: NSLocalizedString("pvd.detail.panelNumbers.modify.check.required", comment: ""))
            self.customView.barcodeTextField.resignFirstResponder()
        }else{
            //如果编辑barcode时没有做任何修改，则不作任何处理,否则内容改变了再做处理
            if barcodeModel.code == barcode {
                self.navigationController?.popViewController(animated: false)
            }else{
                var repeatFlag: Bool = false
                //检查是否存在
                if let _ = self.serialsList.firstIndex(where: {$0.code == barcode}){
                    repeatFlag = true
                }
                //
                if repeatFlag {
                    MBProgressHUD.showToast(parentView: self.view, text: R.string.localizable.duplicated(),delay: 3)
                }else {
                    var validFlag: Bool = false
                    
                    if scanningType == .panel && Tool().isValidPanelNumber(str: barcode){
                        validFlag = true
                    }else if scanningType == .inverter && Tool().isValidInverterNumber(str: barcode){
                        validFlag = true
                    }else if scanningType == .tank  && Tool().isValidInverterNumber(str: barcode) {//TODO: - 校验规则待定
                        validFlag = true
                    }
                    //有效的code：满足正则表达是（此正则表达式从web后台获取）,且长度大于8位
                    if validFlag {
                        self.addModifyData(barcode)
                        self.navigationController?.popViewController(animated: false)
                    }else{//无效的code
                        self.showInvalidBarcodeTipVC(barcode)
                    }
                }
            }
        }
        
    }
    func showInvalidBarcodeTipVC(_ barcode: String){//
        Tool().showAlertViewWithTwoBtns(title: barcode, message: NSLocalizedString("pvd.detail.panalNumbers.scan.suspiciousbarcode.tip", comment: "")) {
            self.customView.barcodeTextField.becomeFirstResponder()
        } yesClosure: {
            self.addModifyData(barcode)
            self.navigationController?.popViewController(animated: false)
        }
    }
    private func addModifyData(_ barcode: String){
        self.barcodeModel.code = barcode
        self.barcodeModel.pvd_id = JobDetailModelHelper.shared.jobDetailModel.id
        self.barcodeModel.operType = DataOperType.Modify.rawValue
        if self.scanningType == .panel {
            //0.插入数据库，此代码放在操作数据库后边，因为broadCast时，有地方（flush upload）会用到本地数据的统计
            DBManager.shared.modifySerialNumberData(model: self.barcodeModel,tableName: panelnumber_table_name)
            //1.增加到当前list中
            self.barcodeModel.original_code = barcode//修改后将original code设置为新的code，作为下次修改的原始code使用
            JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers[self.index] = self.barcodeModel
            JobDetailModelHelper.shared.jobDetailModel.broadCastPanelData()
            //3.上传
            UploadManager.shared.uploadOnePanelNumber(self.barcodeModel)
        }else {//inverter和tank 共用给一个
            //0.插入数据库，此代码放在操作数据库后边，因为broadCast时，有地方（flush upload）会用到本地数据的统计
            DBManager.shared.modifySerialNumberData(model: self.barcodeModel,tableName: inverternumber_table_name)
            //1.增加到当前list中
            self.barcodeModel.original_code = barcode//修改后将original code设置为新的code，作为下次修改的原始code使用
            JobDetailModelHelper.shared.jobDetailModel.pvd_inverter_serial_numbers[self.index] = self.barcodeModel
            JobDetailModelHelper.shared.jobDetailModel.broadCastInverterData()
            //3.上传
            UploadManager.shared.uploadOneInverterNumber(barcodeModel)
        }
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
}
